#include "threadPool.h"
#include "server.h"

void *threadFunc(void * arg)
{
    threadPool_t * pthreadPool = (threadPool_t *)arg;
    
    while(1)
    {
        // 取出任务
        pthread_mutex_lock(&pthreadPool->mutex);
        while(pthreadPool->taskQueue.queueSize == 0)
        {
            pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
        }
        printf("worker got a task!\n");
        MYSQL *mysql = mysql_init(NULL);
        MYSQL *conn= mysql_real_connect(mysql, "localhost", "root", "123", "azupan", 0, NULL, 0);
        int netfd = pthreadPool->taskQueue.pfront->fd;
        Dequeue(&pthreadPool->taskQueue);
        pthread_mutex_unlock(&pthreadPool->mutex);
        
        char buf[1024];
        bzero(buf, sizeof(buf));
        int length = 0;
        //接收登录或注册命令
        recv(netfd, buf, 1024, 0);
        if(buf[strlen(buf) - 1] == '\n')
        {
            buf[strlen(buf) - 1] = '\0';
        }
        printf("%s\n", buf);
        int isLogin = 0;
        if(isLogin == 0)
        {
            if((strcmp(buf, "login")) == 0)
            {
                printf("do s_login\n");
                s_login(netfd,mysql, &isLogin);
            }
            else if((strcmp(buf, "regist")) == 0)
            {
                printf("do s_regist\n");
                //s_regist(netfd, buf);
                mysql_close(mysql);
                close(netfd);            
                continue;
            }
        }
        
        server_worker(netfd, mysql);// 业务代码

        mysql_close(mysql);
        close(netfd);
    }
}

int makeWorker(threadPool_t *pthreadPool)
{
    for(int i = 0; i < pthreadPool->workerNum; ++i)
    {
        pthread_create(&pthreadPool->tidArr[i],NULL,threadFunc,pthreadPool);
    }
    return 0;
}
